import axios from 'axios';

axios.defaults.withCredentials = true;
let server = axios.create({
    baseURL: 'http://localhost:8081/car-system', //请求url
    timeout: 5000, //超时处理
    withCredentials: true //是否跨域
});

axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
//添加一个请求拦截器
server.interceptors.request.use(
    function(config) {
        //在请求发出之前进行一些操作，比如请求头携带内容
        config.headers['Content-Type'] = 'application/json;charset=UTF-8';
        config.headers['Cache-Control'] = 'no-cache';
        if(localStorage.getItem('token')!==null){
            config.headers['Authorization'] = localStorage.getItem('token');
        }
        return config;
    },
    function(error) {
        //Do something with request error
        return error;
    }
);

server.interceptors.response.use((response) => {
        if(response.headers['authorization']!==undefined&&response.headers['authorization']!==null){
            localStorage.removeItem('token');
            localStorage.setItem('token',response.headers['authorization']);
        }

    return response;
}, error => {
    if (401 === error.response.status) {
        let url = window.location.host; /* 获取主机地址和端口号 */
        location.href='http://localhost:8080/#/403';

    } else {
        return Promise.reject(error);
    }
});

export { server, axios };
